//
//  STCountDownTimerView.m
//  YiYueHairdresser
//
//  Created by zhouzhouzhou on 2018/9/30.
//  Copyright © 2018年 YuYiLian. All rights reserved.
//

#import "STCountDownTimerView.h"

@implementation STCountDownTimerView{
    dispatch_source_t countDownTimer;
    NSString * showString;
    UILabel * countDownlab;
    long timerNum;
}

-(UIView*)setCountDownNum:(long)num showString:(NSString*)string{
    if(!countDownlab){
        countDownlab = [[UILabel alloc]initWithFrame:self.bounds];
        countDownlab.textAlignment = NSTextAlignmentCenter;
        countDownlab.font = FONT(13);
        countDownlab.textColor = [UIColor whiteColor];
    }
    timerNum = num;
    showString = string;
    self.backgroundColor = [UIColor orangeColor];
    [self addSubview:countDownlab];
    [self beginCountDown];
    return self;
}


-(void)beginCountDown{
    //全局队列    默认优先级
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式  事件源
    countDownTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    //NSEC_PER_SEC是秒，＊1是每秒
    dispatch_source_set_timer(countDownTimer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
    //设置响应dispatch源事件的block，在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(countDownTimer, ^{
        //回调主线程，在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (timerNum >= 0) {
                int minute = (int)timerNum / 60;
                int second = (int)timerNum % 60;
                countDownlab.text = [NSString stringWithFormat:@"您需要在 %d分%d秒 %@",minute,second,showString];
                
                timerNum--;
            }else{
                //这句话必须写否则会出问题
                dispatch_source_cancel(countDownTimer);
                [self removeAllSubviews];
            }
        });
    });
    //启动源
    dispatch_resume(countDownTimer);
}

@end
